package util;

import bean.StudentBean;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class StudentInfosUtil {
    private static List<StudentBean> studentBeans = new ArrayList();

    private StudentInfosUtil(){}

    public static void readInfos(){
        File file = new File("E:\\javaooGit\\test\\src\\data\\student.txt");

        try (BufferedReader read = new BufferedReader(new FileReader(file))){
            String s;
            while((s = read.readLine()) != null){
                String[] ss = s.split("\\s+");
                StudentBean student = new StudentBean();
                student.setId(Integer.parseInt(ss[0]));
                student.setName(ss[1]);
                student.setClazz(ss[2]);
                student.setBirthday(ss[3]);

                studentBeans.add(student);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void saveStudents(){
        for (StudentBean studentBean : studentBeans) {
            File file = new File("E:\\javaooGit\\test\\src\\data"
                    +File.separator+studentBean.getClazz()+".txt");
            String s = studentBean.getId() + "\t" + studentBean.getName() + "\t"
                    + studentBean.getClazz() + "\t" + studentBean.getBirthday();

            if(!file.exists()){
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            try (FileWriter write = new FileWriter(file, true);
                BufferedWriter out = new BufferedWriter(write)
            ){
                out.write(s);
                out.newLine();
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
